package ils.services;

import ils.application.Configurations;
import ils.application.Scheduler;

import java.util.Date;
import java.util.Iterator;
import java.util.Map;
import java.util.TimerTask;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author: Rejeev Divakaran
 * Date: 7/20/13
 */
public class AuthenticationService {
    private static final Map<String, Date> sessionMap = new ConcurrentHashMap<>();

    public static boolean check(String sessionId){
        Date lastAccessTime = sessionMap.get(sessionId);
        if(lastAccessTime != null && System.currentTimeMillis() < (lastAccessTime.getTime() + Configurations.getSessionTimeoutSec() * 1000)){
            updateLastAccessedTime(sessionId);
            return true;
        }else {
            sessionMap.remove(sessionId);
            return false;
        }
    }

    public static void updateLastAccessedTime(String sessionId){
        sessionMap.put(sessionId, new Date());
    }

    public static boolean authenticate(String username, String password, String sessionId){
        if(username.equals(password)){
            sessionMap.put(sessionId, new Date());
            return true;
        }else {
            sessionMap.remove(sessionId);
            return false;
        }
    }

    public static void logout(String sessionId){
        sessionMap.remove(sessionId);
    }

    static {
        TimerTask timerTask = new TimerTask() {
            @Override
            public void run() {
                Iterator<Map.Entry<String,Date>> iterator = sessionMap.entrySet().iterator();
                while (iterator.hasNext()){
                    if(iterator.next().getValue().getTime() < (System.currentTimeMillis() - Configurations.getSessionTimeoutSec() * 1000)) iterator.remove();
                }
            }
        };
        Scheduler.schedule(timerTask, Configurations.getSessionMapCleaningIntervalSec());
    }
}
